package com.zhao.fishingguideserver.service.impl;

import com.zhao.fishingguideserver.POJO.User;
import com.zhao.fishingguideserver.exception.BusinessException;
import com.zhao.fishingguideserver.mapper.UserMapper;
import com.zhao.fishingguideserver.service.AdminUserService;
import com.zhao.fishingguideserver.utils.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 管理端用户管理服务实现类
 */
@Slf4j
@Service
public class AdminUserServiceImpl implements AdminUserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public List<User> getUserList(String username, String nickName, Integer status) {
        log.debug("查询用户列表，username={}, nickName={}, status={}", username, nickName, status);
        return userMapper.selectAllUsers(username, nickName, status);
    }
    
    @Override
    public Map<String, Object> getUserPage(String username,
                                           String nickName,
                                           Integer status,
                                           Integer page,
                                           Integer pageSize,
                                           String sortBy,
                                           String order) {
        // 参数兜底
        int safePage = (page == null || page < 1) ? 1 : page;
        int safePageSize = (pageSize == null || pageSize < 1 || pageSize > 100) ? 10 : pageSize;
        int offset = (safePage - 1) * safePageSize;
        
        // 排序字段白名单
        String safeSortBy = "createdAt";
        if ("username".equalsIgnoreCase(sortBy)) {
            safeSortBy = "username";
        } else if ("createdAt".equalsIgnoreCase(sortBy)) {
            safeSortBy = "createdAt";
        }
        String safeOrder = "DESC";
        if ("ASC".equalsIgnoreCase(order)) {
            safeOrder = "ASC";
        }
        
        int total = userMapper.countUsers(username, nickName, status);
        List<User> list = userMapper.selectUsersPaged(username, nickName, status, safeSortBy, safeOrder, offset, safePageSize);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        result.put("page", safePage);
        result.put("pageSize", safePageSize);
        return result;
    }
    
    @Override
    public Map<String, Object> getUserDetail(Long userId) {
        log.debug("查询用户详情，userId={}", userId);
        Map<String, Object> userDetail = userMapper.selectUserDetail(userId);
        if (userDetail == null) {
            log.warn("用户不存在，userId={}", userId);
        }
        return userDetail;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserStatus(Long userId, Integer status) {
        log.info("更新用户状态，userId={}, status={}", userId, status);
        int result = userMapper.updateUserStatus(userId, status);
        if (result <= 0) {
            log.warn("用户状态更新失败，userId={}", userId);
        }
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUser(Long userId) {
        log.info("删除用户，userId={}", userId);
        // 注意：由于数据库设置了外键级联删除，删除用户时会自动删除相关数据
        int result = userMapper.deleteUser(userId);
        if (result <= 0) {
            log.warn("用户删除失败，userId={}", userId);
        }
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resetPassword(Long userId, String newPassword) {
        log.info("重置用户密码，userId={}", userId);
        // 密码需要MD5加密（注意：MD5已不够安全，建议升级为BCrypt）
        String encryptedPassword = Md5Util.getMD5String(newPassword);
        int result = userMapper.resetPassword(userId, encryptedPassword);
        if (result <= 0) {
            log.warn("密码重置失败，userId={}", userId);
        }
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserInfo(User user) {
        log.info("更新用户信息，userId={}", user.getUser_id());
        int result = userMapper.updateUser(user);
        if (result <= 0) {
            log.warn("用户信息更新失败，userId={}", user.getUser_id());
        }
        return result;
    }
}

